package com.dinggou.shopjb.fragments;

import android.os.Build;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.dinggou.shopjb.R;
import com.dinggou.shopjb.activitys.CattleBillActivity;
import com.dinggou.shopjb.adapters.HomeAdapter;
import com.dinggou.shopjb.base.BaseActivity;
import com.dinggou.shopjb.base.BaseFragment;
import com.dinggou.shopjb.bean.CalendarBean;
import com.dinggou.shopjb.bean.CalendarDetail;
import com.dinggou.shopjb.bean.DayBean;
import com.dinggou.shopjb.bean.FollowOrderBean;
import com.dinggou.shopjb.bean.FollowOrderRequestBean;
import com.dinggou.shopjb.bean.GifBean;
import com.dinggou.shopjb.bean.HomeData;
import com.dinggou.shopjb.bean.ShopGoodsListBean;
import com.dinggou.shopjb.eventbus.EventCenter;
import com.dinggou.shopjb.eventbus.EventConstants;
import com.dinggou.shopjb.net.ActionCallbackListener;
import com.dinggou.shopjb.utils.CustomerUtil;
import com.dinggou.shopjb.utils.DataUtils;
import com.dinggou.shopjb.utils.FastClickUtil;
import com.dinggou.shopjb.utils.RouteUtil;
import com.dinggou.shopjb.utils.ToolbarUtils;
import com.dinggou.shopjb.utils.Utils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.dinggou.shopjb.view.CreateOrderModule;
import com.zc.mychart.model.GoodsAllBean;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class HomeFragment extends BaseFragment implements HomeAdapter.HomeListener, OnRefreshListener, OnLoadMoreListener {
    private SmartRefreshLayout refreshLayout;
    private RecyclerView rv_list;
    private HomeAdapter homeAdapter;
    private int mPageIndex = 0;//当前页数
    private int mItemsPerPage = 10;//预加载数量
    private int mProfitType = 0;//商城和跟单type
    private FollowOrderRequestBean mFollowOrderRequestBean = new FollowOrderRequestBean();
    private GoodsAllBean mGroupBean;
    private boolean isScroll;//是否在滑动
    private DayBean mDayBean;
    private List<ShopGoodsListBean> displayedItems = new ArrayList<>();
    private List<ShopGoodsListBean> mAllItems = new ArrayList<>();
    private boolean mIsFinish;

    @Override
    protected void initVariable() {
        ToolbarUtils.setStatusTextColor(true, baseActivity);
        refreshLayout.setRefreshFooter(new ClassicsFooter(mContext).setSpinnerStyle(SpinnerStyle.Translate));
        homeAdapter = new HomeAdapter(mContext, this);
        homeAdapter.setFollowRequestBean(mFollowOrderRequestBean);
        ((SimpleItemAnimator) rv_list.getItemAnimator()).setSupportsChangeAnimations(false);
        rv_list.setLayoutManager(new LinearLayoutManager(mContext));
        //优化嵌套卡顿
        rv_list.setHasFixedSize(true);
        rv_list.setNestedScrollingEnabled(false);
        rv_list.setItemAnimator(null); // 禁用动画
        rv_list.setItemViewCacheSize(600);
        RecyclerView.RecycledViewPool recycledViewPool = new
                RecyclerView.RecycledViewPool();
        rv_list.setRecycledViewPool(recycledViewPool);
        rv_list.setAdapter(homeAdapter);
//        baseActivity.loading();
//        new TimeCount(3000, 50){
//            @Override
//            public void onFinish() {
//                super.onFinish();
//                baseActivity.cancelLoading();
//            }
//        }.start();
    }

    @Override
    protected int setContentView() {
        return R.layout.fragment_home;
    }

    @Override
    protected void findViews(View rootView) {
        refreshLayout = (SmartRefreshLayout) $(R.id.refresh_layout);
        rv_list = (RecyclerView) $(R.id.rv_list);
    }

    @Override
    protected void setListeners() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        rv_list.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
//                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//                    isScroll = false;
//                } else {
//                    isScroll = true;
//                }
            }
        });
    }

    @Override
    protected void refreshDataSource() {
        getHomeNetWork();
        getGoodsList();
    }

    private void getHomeNetWork() {
        if (homeAdapter.isNoticeEmpty()) {
            getNewsNoticeList();
        }
        if (homeAdapter.isBannerEmpty()) {
            getImageList();
        }
        if (homeAdapter.isHotEmpty()) {
            getGoodsList();
        }
        if (homeAdapter.isGifEmpty()) {
            getGifList();
        }
        if (homeAdapter.isImportantEmpty()) {
            getImportant();
        }
        if (homeAdapter.isProfitSquareEmpty()) {
            getOrderSquare();
        }
        setIsShowTip();
        if (homeAdapter.isHomeGoodsEmpty()) {
            getHomeGoodsList();
        }
        if (homeAdapter.isDayListEmpty()){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                getCalendarDataAndDay();
            }
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void getCalendarDataAndDay(){
        if (null == mDayBean) {
            getIndexDay();
        } else {
            getCalendarData();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void getIndexDay() {
        List<DayBean> dates = new ArrayList<>();

        LocalDate today = LocalDate.now();
        LocalDate mondayThisWeek = today.with(java.time.temporal.TemporalAdjusters.previousOrSame(java.time.DayOfWeek.MONDAY));
        LocalDate sundayThisWeek = today.with(java.time.temporal.TemporalAdjusters.nextOrSame(java.time.DayOfWeek.SUNDAY));

        DateTimeFormatter shortDateFormatter = DateTimeFormatter.ofPattern("MM/dd");
        DateTimeFormatter fullDateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        for (LocalDate date = mondayThisWeek; date.isBefore(sundayThisWeek.plusDays(1)); date = date.plusDays(1)) {
            DayBean bean = new DayBean();
            bean.day_desc = (date.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.CHINA));
            bean.shortDay = (date.format(shortDateFormatter));
            bean.fullDay = (date.format(fullDateFormatter));
            dates.add(bean);
        }
        if (!dates.isEmpty()){
            mDayBean  = dates.get(0);
        }
        homeAdapter.setDayList(dates);
    }

    private void getCalendarData() {
        String day = "";
        if (null != mDayBean) {
            day = mDayBean.fullDay;
        }
        mAppAction.getCalendarData(day, new ActionCallbackListener<List<CalendarBean>>() {
            @Override
            public void onSuccess(List<CalendarBean> data) {
                homeAdapter.setEconomicsList(data);
            }

            @Override
            public void onFailure(String errorCode, String message) {

            }
        });
    }

    private void setIsShowTip() {
        if (DataUtils.getClientId(mContext).equals("8") || DataUtils.getClientId(mContext).equals("9")){
            homeAdapter.setShowTip(true);
        }else {
            homeAdapter.setShowTip(false);
        }
    }

    private void getHomeGoodsList() {
        if (myApplication.getShopGoodsListBeans() == null){
            myApplication.initAllHomeData(new ActionCallbackListener<HomeData>() {
                @Override
                public void onSuccess(HomeData data) {
                    mAllItems = data.retail;
                    for (int i = 0; i < mAllItems.size(); i++) {
                        if (i < 10){
                            displayedItems.add(mAllItems.get(i));
                        }
                    }
                    homeAdapter.setHomeGoodsList(displayedItems);
                }

                @Override
                public void onFailure(String errorCode, String message) {

                }
            });
        }else {
            mAllItems = myApplication.getShopGoodsListBeans();
            for (int i = 0; i < mAllItems.size(); i++) {
                if (i < 10){
                    displayedItems.add(mAllItems.get(i));
                }
            }
            homeAdapter.setHomeGoodsList(displayedItems);
        }
    }

    private void getOrderSquare() {
        if (myApplication.getSellOrderInfoBeans() == null){
            myApplication.initAllHomeData(new ActionCallbackListener<HomeData>() {
                @Override
                public void onSuccess(HomeData data) {
                    homeAdapter.setProfitSquareList(data.orderProfit);
                }

                @Override
                public void onFailure(String errorCode, String message) {

                }
            });
        }else {
            homeAdapter.setProfitSquareList(myApplication.getSellOrderInfoBeans());
        }
    }

    private void getImportant() {
        if (myApplication.getImportantBean() == null){
            myApplication.initAllHomeData(new ActionCallbackListener<HomeData>() {
                @Override
                public void onSuccess(HomeData data) {
                    homeAdapter.setImportantData(data.important);
                }

                @Override
                public void onFailure(String errorCode, String message) {

                }
            });
        }else {
            homeAdapter.setImportantData(myApplication.getImportantBean());
        }
    }


    private void getNewsNoticeList() {
        if (myApplication.getNewsNoticeBeans() == null){
            myApplication.initAllHomeData(new ActionCallbackListener<HomeData>() {
                @Override
                public void onSuccess(HomeData data) {
                    homeAdapter.setNewsNoticeList(data.notice);
                }

                @Override
                public void onFailure(String errorCode, String message) {

                }
            });
        }else {
            homeAdapter.setNewsNoticeList(myApplication.getNewsNoticeBeans());
        }
    }

    private void getImageList() {
        if (myApplication.getBannerBeans() == null){
            myApplication.initAllHomeData(new ActionCallbackListener<HomeData>() {
                @Override
                public void onSuccess(HomeData data) {
                    homeAdapter.setImageList(data.banner);
                }

                @Override
                public void onFailure(String errorCode, String message) {

                }
            });
        }else {
            homeAdapter.setImageList(myApplication.getBannerBeans());
        }
    }

    private void getGoodsList() {
        if (myApplication.getAllList().isEmpty()) {
            myApplication.initAllHomeData(new ActionCallbackListener<HomeData>() {
                @Override
                public void onSuccess(HomeData data) {
                    homeAdapter.setGoodsList(data.contract);
                }

                @Override
                public void onFailure(String errorCode, String message) {
                    errorHandler(errorCode, message);
                }
            });
        } else {
            homeAdapter.setGoodsList(myApplication.getAllList());
        }
    }

    private void getGifList() {
        if (myApplication.getGifMap().isEmpty()) {
            myApplication.initAllHomeData(new ActionCallbackListener<HomeData>() {
                @Override
                public void onSuccess(HomeData data) {
                    Map<String, GifBean> gifBeanMap = new HashMap<>();
                    for (int i = 0; i < data.gif.size(); i++) {
                        gifBeanMap.put(data.gif.get(i).type, data.gif.get(i));
                    }
                    homeAdapter.setGifList(gifBeanMap);
                }

                @Override
                public void onFailure(String errorCode, String message) {
                    errorHandler(errorCode, message);
                }
            });
        } else {
            homeAdapter.setGifList(myApplication.getGifMap());
        }
    }

    @Override
    public void onClickBanner(String url) {
        RouteUtil.toWebViewActivity(baseActivity, url);
    }

    @Override
    public void onClickHotPro(GoodsAllBean bean) {
        if (FastClickUtil.isFastClick()) {
            return;
        }
        if (bean != null) {
            RouteUtil.toMarketActivity(baseActivity, bean.pro_code);
        }
    }

    @Override
    public void onClickWelfare() {

    }

    @Override
    public void onClickInvestSchool() {
        RouteUtil.toInvestSchoolNewActivity(baseActivity);
    }

    @Override
    public void onClickProfit() {

    }

    @Override
    public void onClickHotActivity() {

    }

    @Override
    public void onClickShopMall() {

    }

    @Override
    public void onClickFollowOrder() {
        RouteUtil.toFollowOrderCenterActivity((BaseActivity) mContext);
    }

    @Override
    public void onClickProfitSquare() {
        //牛单播报
        gotoActivity(mContext, CattleBillActivity.class, null);
    }

    @Override
    public void onClickCustomService() {
        CustomerUtil.customerService(mContext);
    }

    @Override
    public void onClickRefresh() {

    }

    @Override
    public void onClickImportantData(String url, String title) {
        if (!url.isEmpty()) {
            RouteUtil.toWebViewActivity((BaseActivity) mContext, url);
        }
    }

    @Override
    public void onClickListType(int type) {
        mProfitType = type;
        if (mProfitType == 0) {
            if (homeAdapter.isHomeGoodsEmpty()) {
                getHomeGoodsList();
            } else {
                homeAdapter.notifyBottomTypeList();
            }
        } else if (mProfitType == 1){
            if (homeAdapter.isFollowEmpty()) {
                getFollowList();
            } else {
                homeAdapter.notifyBottomTypeList();
            }
        } else {
            if (homeAdapter.isEconomicsEmpty()){
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    getCalendarDataAndDay();
                }
            } else {
                homeAdapter.notifyBottomTypeList();
            }
        }
    }

    private void getFollowList() {
        mAppAction.getFollowList(1, mFollowOrderRequestBean.openTime, mFollowOrderRequestBean.contract, mFollowOrderRequestBean.follow, mFollowOrderRequestBean.level, new ActionCallbackListener<List<FollowOrderBean>>() {
            @Override
            public void onSuccess(List<FollowOrderBean> data) {
                if (!data.isEmpty()) {
                    homeAdapter.setFollowList(Utils.completionFollow(data));
                } else {
                    homeAdapter.setFollowList(new ArrayList<>());
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {

            }
        });
    }

    @Override
    public void onClickRecharge() {

    }

    @Override
    public void onClickNotice() {

    }

    @Override
    public void onClickTicket() {
        RouteUtil.toRechargeActivity(baseActivity);
    }

    @Override
    public void onClickNewTeacher() {

    }

    @Override
    public void onClickSign() {

    }

    @Override
    public void onChangeFollowRequestBean(FollowOrderRequestBean bean) {
        mFollowOrderRequestBean = bean;
        getFollowList();
    }

    @Override
    public void onClickMessage() {
        if (isUserValidLogin()) {
            RouteUtil.toMessageActivity((BaseActivity) mContext);
        }
    }

    @Override
    public void onClickTask() {

    }

    @Override
    public void onClickLuckyDay() {

    }

    @Override
    public void onClickBuyGoods(ShopGoodsListBean bean) {
        RouteUtil.toGoodsImageDetailActivity(baseActivity, bean);
    }

    @Override
    public void onClickFollowGroupBean(GoodsAllBean bean) {
        this.mGroupBean = bean;
    }

    @Override
    public void onClickCalendar(CalendarBean bean) {
        mAppAction.getCalendarDetail(bean.data_id, new ActionCallbackListener<CalendarDetail>() {
            @Override
            public void onSuccess(CalendarDetail data) {
                if (null != data) {
                    RouteUtil.toCalendarDetailActivity(baseActivity, data);
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {

            }
        });
    }

    @Override
    public void onClickDay(DayBean bean) {
        mDayBean = bean;
        getCalendarData();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        if (mProfitType != 0){
            refreshLayout.finishLoadMore(500);
            return;
        }
        mPageIndex++;
        int start = mPageIndex * mItemsPerPage;
        int end = Math.min(start + mItemsPerPage, mAllItems.size());
        if (end == mAllItems.size() && mIsFinish){
            refreshLayout.finishLoadMore(500);
            return;
        }
        for (int i = 0; i < mAllItems.size(); i++) {
            if (i >= start && i < end){
                displayedItems.add(mAllItems.get(i));
                if (end == mAllItems.size()){
                    mIsFinish = true;
                }
            }
        }
        homeAdapter.setHomeGoodsList(displayedItems);
        refreshLayout.finishLoadMore(500);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        if (mProfitType != 0){
            getHomeNetWork();
            refreshLayout.finishRefresh(2000);
        }else {
            mPageIndex = 0;
            displayedItems.clear();
            for (int i = 0; i < mAllItems.size(); i++) {
                if (i < 10) {
                    displayedItems.add(mAllItems.get(i));
                }
            }
            homeAdapter.setHomeGoodsList(displayedItems);
            getHomeNetWork();
            refreshLayout.finishRefresh(2000);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        homeAdapter.updateNewer();
    }

    @Override
    protected void onEventComming(EventCenter eventCenter) {
        super.onEventComming(eventCenter);
        int eventCode = eventCenter.getEventCode();
        switch (eventCode) {
            case EventConstants.EVENTCODE_UPDATE_PRO_PRICE:
//                if (isScroll) return;
                //开始更新列表
                if (!myApplication.getAllList().isEmpty()) {
                    getGoodsList();
                }

                if (CreateOrderModule.getInstance().getOrderCreateDialog() != null && CreateOrderModule.getInstance().getOrderCreateDialog().isShowing()) {
                    CreateOrderModule.getInstance().setNewPrice();
                }
                break;
            case EventConstants.EVENTCODE_UPDATE_PRO_FOLLOW_PRICE:
//                if (isScroll) return;
                if (mProfitType == 1 && !homeAdapter.isFollowEmpty()) {
                    homeAdapter.setFollowList(Utils.completionFollow(homeAdapter.getmFollowList()));
                }
                break;
        }
    }
}
